package com.chunlin.servlet.cookieandseesion;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/getCookie")
public class GetCookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //后续客户端再次发送请求的时候,cookie内容就会出现在请求中
        //这样服务器就可以拿到cookie的内容了(浏览器中会进行保存的)
        //获取到这次请求中的Cookie
        Cookie[] cookies = req.getCookies();
        StringBuilder cookieString = new StringBuilder();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookieString.append(cookie.getName() + " : " + cookie.getValue());
                cookieString.append("<br>");
            }
            cookieString.delete(cookieString.length() - 4, cookieString.length());
            resp.setContentType("text/html;charset=utf8");
        }
        resp.getWriter().write(cookieString.toString());
    }
}
